package com.hboxs.asl.controller.asl.member;

import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.Pageable;
import com.hboxs.asl.Setting;
import com.hboxs.asl.controller.asl.BaseController;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.entity.MemberCertification;
import com.hboxs.asl.service.*;
import com.hboxs.asl.util.ImageUtils;
import com.hboxs.asl.util.SettingUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;

/**
 * Controller - 会员中心
 */
@Controller("aslProfileController")
@RequestMapping("/weChat/profile")
public class ProfileControl extends BaseController {

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "fileServiceImpl")
    private FileService fileService;
    @Resource(name = "tradeServiceImpl")
    private TradeService tradeService;
    @Resource(name = "orderServiceImpl")
    private OrderService orderService;
    @Resource(name = "cartServiceImpl")
    private CartService cartService;
    @Resource(name = "memberCertificationServiceImpl")
    private MemberCertificationService memberCertificationService;

    protected Logger logger = Logger.getLogger(getClass().getName());

    // 未支付
    private static final Integer PAY_ORDERS = 0;
    // 待发货
    private static final Integer SHIP_ORDERS = 1;
    // 退换货
    private static final Integer RETURN_ORDERS = 2;
    // 待评价
    private static final Integer EVALUATION_ORDERS = 3;
    // 全部
    private static final Integer ALL_ORDERS = 4;
    // 待收货
    private static final Integer RECEIPT_ORDERS = 5;

    /**
     * 会员中心
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(ModelMap modelMap, Pageable pageable) {
        try {
            Member member = memberService.getCurrent();
            if (member!=null){
                modelMap.addAttribute("count", cartService.getTotalNumberOfGoodsInCart(member.getCart()));
                modelMap.addAttribute("payment", orderService.findPage(member, pageable, PAY_ORDERS).getTotal());
                modelMap.addAttribute("ship", orderService.findPage(member, pageable, SHIP_ORDERS).getTotal());
                modelMap.addAttribute("receipt", orderService.findPage(member, pageable, RECEIPT_ORDERS).getTotal());
                modelMap.addAttribute("evaluation", orderService.findPage(member, pageable, EVALUATION_ORDERS).getTotal());
                modelMap.addAttribute("return", orderService.findPage(member, pageable, RETURN_ORDERS).getTotal());
                modelMap.addAttribute("member", member);
            }
            return "/yijing/center";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/yijing/404";
    }


    /**
     * 主播认证跳转
     */
    @RequestMapping(value = "/certification", method = RequestMethod.GET)
    public String certification(ModelMap modelMap, Pageable pageable) {
        return "/yijing/center_certification";
    }

    /**
     * 主播认证提交
     */
    @RequestMapping(value = "/identify", method = RequestMethod.POST)
    public
    @ResponseBody
    Object identify(MemberCertification memberCertification) throws InvocationTargetException, IllegalAccessException {

        Member member = memberService.getCurrent();
        if (member == null) {
            return JsonMessage.USER_NOT_LOGIN;
        }
        MemberCertification pMemberCertification = member.getMemberCertification();
        if (pMemberCertification != null) {
            BeanUtils.copyProperties(memberCertification, pMemberCertification, "id", "member", "merchant");
            pMemberCertification.setStatus(MemberCertification.Status.reviewing);
            memberCertificationService.update(pMemberCertification);

            // 清空推荐码
            member.setCode(null);
            memberService.update(member);

            return JsonMessage.success(member.getMemberCertification().getStatus().toString());
        }

        // 等待审核
        memberCertification.setMerchant(member.getMerchant());
        memberCertification.setStatus(MemberCertification.Status.reviewing);
        memberCertificationService.save(memberCertification);
        member.setMemberCertification(memberCertification);
        memberService.update(member);

        return JsonMessage.success("提交成功，等待审核");

    }


    /**
     * 充值
     *
     * @return
     */
    @RequestMapping(value = "/recharge", method = RequestMethod.GET)
    public String recharge(HttpServletRequest request, ModelMap model) {
        Member member = memberService.getCurrent();
        model.addAttribute("member", member);
        return "/yijing/recharge";
    }


    /**
     * 更新GET
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = "text/html; charset=UTF-8")
    public String update(Member member,
                         Float x1, Float y1, Float x2, Float y2, Float w, Float h, MultipartFile avatorImage,
                         HttpServletRequest request, RedirectAttributes redirectAttributes) {

        Member pMember = memberService.find(member.getId());


        if (pMember == null) {
            addFlashMessage(redirectAttributes, ERROR_MESSAGE);
            return "redirect:/m/pf/index.htm";
        }
        if (x1 != null && y1 != null && w != null && h != null) {

            // 处理头像
            String imageName = ImageUtils.cutImage(avatorImage, x1.intValue(), y1.intValue(), w.intValue(), h.intValue());
            // 设置头像
            member.setAvator(imageName);
        } else {
            member.setAvator(pMember.getAvator());
        }

        Setting setting = SettingUtils.get();

        if (!setting.getIsDuplicateEmail() && !memberService.emailUnique(pMember.getEmail(), member.getEmail())) {
            return ERROR_VIEW;
        }

        if (pMember.getIsLocked() && !member.getIsLocked()) {
            member.setLoginFailureCount(0);
            member.setLockedDate(null);
        } else {
            member.setIsLocked(pMember.getIsLocked());
            member.setLoginFailureCount(pMember.getLoginFailureCount());
            member.setLockedDate(pMember.getLockedDate());
        }


        BeanUtils.copyProperties(member, pMember, "isEnabled", "password", "memberRank", "username", "point", "amount", "balance", "registerIp", "loginIp", "loginDate", "safeKey", "cart", "orders", "deposits", "payments", "couponCodes", "receivers", "reviews", "consultations", "favoriteProducts", "productNotifies", "inMessages", "outMessages");
        memberService.update(pMember);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:/m/pf/index.htm";
    }


    /**
     * 验证当前密码
     */
    @RequestMapping(value = "/check_current_password", method = RequestMethod.GET)
    public
    @ResponseBody
    boolean checkCurrentPassword(String currentPassword) {
        if (StringUtils.isEmpty(currentPassword)) {
            return false;
        }
        Member member = memberService.getCurrent();
        return StringUtils.equals(DigestUtils.md5Hex(currentPassword), member.getPassword());
    }

    /**
     * 更新
     */
    @RequestMapping(value = "/updatePass", method = RequestMethod.POST)
    public String update(String currentPassword, String password, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(currentPassword)) {
            return ERROR_VIEW;
        }
        if (!isValid(Member.class, "password", password)) {
            return ERROR_VIEW;
        }
        Setting setting = SettingUtils.get();
        if (password.length() < setting.getPasswordMinLength() || password.length() > setting.getPasswordMaxLength()) {
            return ERROR_VIEW;
        }
        Member member = memberService.getCurrent();
        if (!StringUtils.equals(DigestUtils.md5Hex(currentPassword), member.getPassword())) {
            return ERROR_VIEW;
        }
        member.setPassword(DigestUtils.md5Hex(password));
        memberService.update(member);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:/m/pf/index.htm";
    }

}
